package com.tau.iplayer.client.dialogs;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.gadgets.client.gwtrpc.GadgetsGwtRpc;
import com.google.gwt.gadgets.client.osapi.people.Person;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.tau.iplayer.client.DataStoreService;
import com.tau.iplayer.client.DataStoreServiceAsync;
import com.tau.iplayer.client.IPlayerUtils;
import com.tau.iplayer.client.models.Track;
import com.tau.iplayer.client.models.TrackTransaction;

public class SendTrackDialog extends DialogBox {

	private static final boolean IS_MULTIPLE_SELECT = true;
	private static final boolean IS_AUTO_HIDE = false;
	private static final boolean IS_MODAL = false;
	private static final boolean IS_ANIMATED = true;
	private static final boolean IS_GLASS = true;
	private static final String HEADER = "Send Track";
	private String senderID;
	private List<Person> friends;
	private Track track;
	private ListBox toListBox;
	private TextBox titleTextBox;
	private TextBox artistTextBox;
	private TextArea textArea;

	public SendTrackDialog(String senderID, List<Person> friends, Track track) {
		this.senderID = senderID;
		this.friends = friends;
		this.track = track;
		setAutoHideEnabled(IS_AUTO_HIDE);
		setModal(IS_MODAL);
		setAnimationEnabled(IS_ANIMATED);
		setGlassEnabled(IS_GLASS);
		setText(HEADER);
		createContents();
	}

	private void createContents() {
		DockPanel dockPanel = new DockPanel();

		HorizontalPanel horizontalPanel = new HorizontalPanel();
		final Button sendButton = new Button("Send");
		sendButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				handleSendClicked();
			}
		});
		sendButton.setStyleName("button");
		sendButton.setEnabled(false);
		Button cancelButton = new Button("Cancel");
		cancelButton.setStyleName("button");
		cancelButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				handleCancelClick();
			}
		});
		horizontalPanel.add(sendButton);
		horizontalPanel.add(cancelButton);
		horizontalPanel.setSpacing(3);
		dockPanel.add(horizontalPanel, DockPanel.SOUTH);
		dockPanel.setCellHorizontalAlignment(horizontalPanel,
				HasHorizontalAlignment.ALIGN_CENTER);
		
		Grid msgGrid = new Grid(1,2);
		msgGrid.setText(0, 0, "Message:");
		msgGrid.getCellFormatter().setStyleName(0, 0, "standardLabel");
		textArea = new TextArea();
		textArea.setStyleName("addSongDialogTextBox");
		msgGrid.setWidget(0, 1, textArea);
		dockPanel.add(msgGrid, DockPanel.SOUTH);

		Grid formGrid = new Grid(4, 2);
		formGrid.setText(0, 0, "To:");
		formGrid.getCellFormatter().setStyleName(0, 0, "standardLabel");
		toListBox = new ListBox(IS_MULTIPLE_SELECT);
		Collections.sort(friends, new Comparator<Person>() {

			@Override
			public int compare(Person o1, Person o2) {
				return o1.getDisplayName().compareToIgnoreCase(
						o2.getDisplayName());
			}
		});
		for (Person friend : friends) {
			toListBox.addItem(friend.getDisplayName());
		}
		toListBox.setStyleName("contactsListBox");
		toListBox.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				checkRestrications(sendButton);
			}
		});
		formGrid.setWidget(0, 1, toListBox);

		formGrid.setText(1, 0, "Title:");
		formGrid.getCellFormatter().setStyleName(1, 0, "standardLabel");
		titleTextBox = new TextBox();
		titleTextBox.setText(track.getTitle());
		titleTextBox.setStyleName("addSongDialogTextBox");
		titleTextBox.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				checkRestrications(sendButton);
			}
		});
		formGrid.setWidget(1, 1, titleTextBox);

		formGrid.setText(2, 0, "Artist:");
		formGrid.getCellFormatter().setStyleName(2, 0, "standardLabel");
		artistTextBox = new TextBox();
		if (track.getArtist() != null && track.getArtist().length() > 0) {
			artistTextBox.setText(track.getArtist());
		}
		artistTextBox.setStyleName("addSongDialogTextBox");
		formGrid.setWidget(2, 1, artistTextBox);

		formGrid.setText(3, 0, "Duration:");
		formGrid.getCellFormatter().setStyleName(3, 0, "standardLabel");
		formGrid.setText(3, 1, IPlayerUtils.formatTime(track.getDuration()));
		formGrid.getCellFormatter().setStyleName(3, 1, "standardLabel");
		dockPanel.add(formGrid, DockPanel.WEST);
		
		Image thumbnailImage = new Image(track.getThumbnailURL());
		dockPanel.add(thumbnailImage, DockPanel.CENTER);

		setWidget(dockPanel);
		thumbnailImage.addLoadHandler(new LoadHandler() {

			@Override
			public void onLoad(LoadEvent event) {
				handleThumbnailOnLoad();
			}
		});
	}

	private void handleThumbnailOnLoad() {
		center();
	}

	private void handleCancelClick() {
		this.hide();

	}

	private void handleSendClicked() {
		DataStoreServiceAsync dataStoreService = GWT
				.create(DataStoreService.class);
		GadgetsGwtRpc.redirectThroughProxy((ServiceDefTarget) dataStoreService);
		for(int i=0; i<toListBox.getItemCount(); i++) {
			if(toListBox.isItemSelected(i)) {
				TrackTransaction transaction = new TrackTransaction();
				transaction.setMessage(textArea.getValue());
				transaction.setReceiverID(friends.get(i).getId());
				transaction.setSenderID(senderID);
				transaction.setThumbnailURL(track.getThumbnailURL());
				transaction.setVideoID(track.getVideoID());
				transaction.setTitle(titleTextBox.getValue());
				transaction.setArtist(artistTextBox.getValue());
				transaction.setDuration(track.getDuration());
				
				dataStoreService.storeTrackTransaction(transaction, new AsyncCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
			}
		}
		SendTrackDialog.this.hide();
	}

	/**
	 * @param sendButton
	 */
	private void checkRestrications(final Button sendButton) {
		boolean isEnabled = !IPlayerUtils.isEmpty(titleTextBox
				.getValue()) && (toListBox.getSelectedIndex() != -1);
		sendButton.setEnabled(isEnabled);
	}

}
